<template>
    <div class="container">
        <el-page-header @back="goBack" content="价格表"></el-page-header>
        <!-- 分类 -->
        <div class="type-state e-m-t-45 e-m-b-30">
            <span class="e-p-l-30 e-p-r-30" v-for="(item, index) in statusArr" :key="index" :class="{ 'on': state == item.value }" @click="goPage(item.value)">{{ item.name }}</span>
        </div>
        <div class="e-m-t-45">
            <div class="flex">
                <div class="">
                    <el-button type="primary" plain @click="download" icon="el-icon-edit">下载价格表</el-button>
                </div>
                <!-- <el-form :inline="true" class="demo-form-inline e-m-l-80 e-flex-1 text-right">
                    <el-form-item>
                        <el-checkbox v-model="isUseable">包含未启用</el-checkbox>
                    </el-form-item>
                    <el-form-item>
                        <el-input placeholder="关键词搜索" prefix-icon="el-icon-search" v-model="key" clearable
                            @clear="getList" @input="$throttle(getList(true), 3000)"></el-input>
                    </el-form-item>
                    <el-form-item class="e-m-r-0">
                        <el-button type="primary" @click="getList">查询</el-button>
                    </el-form-item>
                </el-form> -->
            </div>
            <el-row :gutter="20">
                <!-- 原内容区域 -->
                <el-col :span="24">
                    <!-- <div class="e-m-b-30">
                        <el-button type="primary" plain @click="download" icon="el-icon-edit">下载价格表</el-button>
                    </div> -->
                    <el-table tooltip-effect="dark" :data="tableData" :span-method="objectSpanMethod" border
                        style="width: 1000px; margin-top: 20px">
                        <el-table-column prop="large" label="类型" width="200">
                        </el-table-column>
                        <el-table-column prop="name" label="可回收物" width="200">
                        </el-table-column>
                        <el-table-column prop="onsiteprice" label="上门回收价(元/KG)">
                            <template slot-scope="scope">
                                <span>{{ utils.formatMoney(scope.row.onsiteprice) }}</span>
                                <!-- <el-input v-model="scope.row.price" placeholder="请输入价格"
                                    :rules="[{ pattern: /^(?!0\d)(\d+)(\.\d{1,2})?$/, message: '请输入有效数字' }]">
                                </el-input> -->
                            </template>
                        </el-table-column>
                        <el-table-column prop="storeprice" label="站点回收价(元/KG)">
                            <template slot-scope="scope">
                                <span>{{ utils.formatMoney(scope.row.storeprice) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="packprice" label="预估出库价(元/KG)">
                            <template slot-scope="scope">
                                <span>{{ utils.formatMoney(scope.row.packprice) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column width="100" label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" icon="el-icon-edit"
                                    @click="showEdit(scope.row)">修改价格</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
        </div>

        <!-- 新建编辑可回收物 -->
        <el-dialog :title="isEdit ? '修改' : '新建'" :visible.sync="createDialogVisible" width="800px" :append-to-body="true">
            <el-form ref="ruleForm" :model="form" :rules="rules" label-width="130px" v-if="createDialogVisible">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="减碳量百分比" prop="carbon">
                    <el-input v-model="form.carbon"></el-input>
                </el-form-item> -->
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item>
                <el-form-item label="默认上门价" prop="onsiteprice">
					<div class="flex" style="align-items: center;">
						<el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.onsiteprice.price">
							<template slot="prepend">价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
						<el-switch v-model="form.onsiteprice.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15 e-m-t-15" style="align-items: center;" v-if="form.onsiteprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.onsiteprice.minprice">
							<template slot="prepend">允许修改最低价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;" v-if="form.onsiteprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.onsiteprice.highprice">
							<template slot="prepend">允许修改最高价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
				</el-form-item>
                <el-form-item label="默认站点价" prop="storeprice">
					<div class="flex" style="align-items: center;">
						<el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.storeprice.price">
							<template slot="prepend">价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
						<el-switch v-model="form.storeprice.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15 e-m-t-15" style="align-items: center;" v-if="form.storeprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.storeprice.minprice">
							<template slot="prepend">允许修改最低价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;" v-if="form.storeprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.storeprice.highprice">
							<template slot="prepend">允许修改最高价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
				</el-form-item>
                <el-form-item label="预估出库价" prop="packprice">
                    <el-input v-model="form.packprice">
                        <span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
                    </el-input>
                </el-form-item>
                <el-form-item label="是否按重量" prop="estimatedweight" v-if="!isEdit">
                    <el-switch v-model="form.isweighing"></el-switch>
                </el-form-item>
                <el-form-item v-if="form.isweighing == false" label="按件估重 （选填）" prop="estimatedweight">
                    <el-input v-model="form.estimatedweight"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="form.remarks" type="textarea"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="createDialogVisible = false">取消</el-button>
                <el-button v-if="isEdit" type="primary" @click="edit">编辑</el-button>
                <el-button v-else type="primary" @click="create">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    mapState
} from 'vuex';

export default {
    layout: 'admin',
    head() {
        return {
            title: '价格表-' + this.websetting.name
        }
    },
    data() {
        return {
            loading: false,
            key: '',
            tableData: [],
            dialogVisible: false,
            state: 1,
            statusArr: [
                {
                    name: '默认价格',
                    value: 1
                },
                {
                    name: '上门价',
                    value: 2
                },
                {
                    name: '站点价',
                    value: 3
                },
                {
                    name: '客户组价',
                    value: 4
                }
            ],
            //新建弹窗显示
            createDialogVisible: false, 
            isEdit: true,
            // 新建表单
            form: {
                "typeid":0,
                "id": 0,
                "name": "",
                "carbon": 1,
                "pic": "",
                "sort": null,
                "packprice": null,
                "isweighing": true,
                "onsiteprice": {
                    "edit": true,
                    "price": null,
                    "minprice": null,
                    "highprice": null
                },
                "storeprice": {
                    "edit": true,
                    "price": null,
                    "minprice": null,
                    "highprice": null
                },
                "estimatedweight": null
            },
            rules: {
                name: [
                    { required: true, message: '请输入可回收物名称', trigger: 'blur' }
                ],
                // mobile: [
                //     { required: true, message: '请输入手机号', trigger: 'blur' },
                //     { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
                // ],
            },
        }
    },
    mounted() {
        this.getList()
    },
    computed: {
        ...mapState({
            userdetail: state => state.userdetail
        })
    },
    methods: {
        // 返回上一页
        goBack() {
            this.$router.go(-1)
        },
        // 跳转页面
        goPage(value){
            switch(value){
                case 1:
                    this.$router.push(`/price/default`)
                    break
                case 2:
                    this.$router.push(`/price/onsite`)
                    break
                case 3:
                    this.$router.push(`/price/store`)
                    break
                case 4:
                    this.$router.push(`/price/enterprise`)
                    break
            }
        },
        // 获取数据
        getList() {
            this.tableData = []
            this.$axios.get('/Waste/Price/Overview').then(res => {
                console.log(res)
                // this.tableData = res
                // let arr = []
                // res.forEach(item => {
                //     item.product.forEach(i => {
                //         let obj = {}
                //         obj.large = item.typenames || item.name
                //         obj.name = i.name
                //         obj.onsiteprice = i.onsiteprice
                //         obj.storeprice = i.storeprice
                //         obj.id = i.id
                //         arr.push(obj)
                //     })
                // });

                // this.tableData = arr
                this.tableData = this.flattenData(res.type)
                console.log(this.tableData)
                this.loading = false

            })
        },
        flattenData(data, level = 0, parentPath = []) {
            let result = [];
            data.forEach(item => {
                const currentPath = [...parentPath, item];
                item.product.filter((item)=>item.usestate == '已启用').forEach(product => {
                    result.push({
                        ...product,
                        id: product.id,
                        name: product.name,
                        onsiteprice: product.onsiteprice,
                        storeprice: product.storeprice,
                        large: item.name,
                        typeid: item.id,
                        level: level,
                        isCategory: true,
                    });
                })
                // 递归处理子类型
                if (item.type && item.type.length > 0) {
                    // console.log(currentPath)
                    const childData = this.flattenData(item.type, level + 1, currentPath);
                    console.log('递归处理子类型-childData:', childData)
                    childData.forEach((cell) => {
                        result = result.concat([{
                            ...cell,
                            id: cell.id,
                            name: `${cell.large}-${cell.name}`,
                            // name: this.getSubCategoryName(currentPath),
                            onsiteprice: cell.onsiteprice,
                            storeprice: cell.storeprice,
                            large: currentPath[0].name,
                            typeid: currentPath[0].id,
                            level: cell.level,
                            isCategory: cell.isCategory,
                        }]);
                    })

                }
            })
            return result;
        },
        // 合并
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            // console.log(rowIndex, columnIndex,'ssss')
            // console.log(row, 'aaaaa')

            let mergeLength = 1;//需要进行横纵合并的列
            if (columnIndex < mergeLength) {
                let finArray = [1, 1];
                // 处理行数据
                let cgname = 'large' //合并单元格的主键依据，一般为第一列的值
                if (rowIndex === 0 || row[cgname] !== this.tableData[rowIndex - 1][cgname]) {
                    let rowspan = 1;
                    //计算需要进行合并操作的行
                    for (let i = 0; i < this.tableData.length - 1; i++) {
                        // 只合并连续的
                        if (this.tableData[i][cgname] === row[cgname] && this.tableData[i + 1][cgname] === row[cgname]) {
                            rowspan++;
                        }
                    }
                    finArray[0] = rowspan;
                } else {
                    finArray[0] = 0;
                }

                return finArray
            }
        },
        // 下载价格表
        download() {
            this.$axios.post('/Waste/Price/OverviewDownload', {
                
            }, {
                responseType: 'blob'
            }).then(res => {
                console.log(res)
                let content = res;
                let fileName = '价格表.xls'
                this.utils.saveAndExport(content, fileName)
            })
        },
        // 发起修改
        showEdit(obj) {
            console.log('发起修改',obj)
            this.createDialogVisible = true;
            this.isEdit = true
            this.form = {
                id: obj.id,
                typeid: obj.typeid,
                name: obj.name,
                typename: obj.typename,
                carbon: obj.carbon,
                isweighing: obj.isweighing,
                sort: obj.sort,
                packprice: obj.packprice,
                onsiteprice: {
                    edit: obj.editonsiteprice,
                    price: obj.onsiteprice,
                    minprice: obj.onsiteminprice,
                    highprice: obj.onsitehighprice
                },
                storeprice: {
                    edit: obj.editstoreprice,
                    price: obj.storeprice,
                    minprice: obj.storeminprice,
                    highprice: obj.storehighprice
                },
                estimatedweight: obj.estimatedweight,
                remarks: obj.remarks,
                usestate: obj.usestate
            }
        },
        // 新建
        create() {
            // this.$refs.ruleForm.validate(valid => {
            //     if (valid) {
            //         this.$axios.post('/Waste/Product/Create', this.form).then((res) => {
            //             this.createDialogVisible = false
            //             this.$message.success('提交成功');
            //         })
            //     } else {
            //         console.log('验证失败');
            //     }
            // });
        },
        // 修改可回收物
        edit() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    this.$axios.post('/Waste/Product/Edit', this.form).then((res) => {
                        this.createDialogVisible = false
                        this.$message.success('修改成功');
                        this.getList(true)
                    })
                } else {
                    console.log('验证失败');
                }
            });
        },
        // 提交批量修改
        submitBatch() {
            const validData = this.tableData.filter(item =>
                item.id && item.price &&
                /^(?!0\d)(\d+)(\.\d{1,2})?$/.test(item.price)
            )

            if (validData.length === 0) {
                this.$message.warning('请填写有效的修改数据')
                return
            }

            this.$confirm('点击确定批量修改价格, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post('/Waste/Price/Set',
                    validData.map(item => ({
                        id: item.id,
                        price: item.price
                    }))
                ).then(() => {
                    this.$message.success('批量修改成功')
                    this.dialogVisible = false
                    // this.getList()
                })
            })
        },
        // 处理类型选择变化
        handleProductChange(index) {
            const selectedId = this.batchForm[index].productId;
            // 检查是否有重复选择
            const hasDuplicate = this.batchForm.some((item, i) =>
                i !== index && item.productId === selectedId
            );

            if (hasDuplicate) {
                this.$message.warning('该类型已存在，请勿重复选择');
                this.batchForm[index].productId = null; // 清空错误选择
            }
        },
        handleHistoryDetail(detail) {
            // 可以在这里处理详情数据
            console.log('历史详情:', detail)
        }
    }
}
</script>

<style lang="scss" scoped></style>